package com.joint.web.action.finance;

import com.fz.us.base.bean.BaseEnum;
import com.fz.us.base.bean.Pager;
import com.fz.us.base.util.LogUtil;
import com.google.common.collect.Lists;
import com.joint.base.bean.FlowEnum;
import com.joint.base.entity.*;
import com.joint.base.exception.users.DutyNotExistsException;
import com.joint.base.exception.workflow.PcfgNotExistException;
import com.joint.base.util.DataUtil;
import com.joint.core.entity.finance.FinancialAnalysis;
import com.joint.core.service.FinancialAnalysisService;
import com.joint.web.action.BaseFlowAction;
import net.sf.json.JSONObject;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.ParentPackage;

import javax.annotation.Resource;
import java.util.*;

/**
 * Created by ZhuChunXiao on 2017/3/9.
 */
@ParentPackage("finance")
public class AjaxFinancialanalysisAction extends BaseFlowAction {
    @Resource
    private FinancialAnalysisService financialAnalysisService;

    private FinancialAnalysis financialAnalysis;
    private Users loginUser;
    private String viewtype;
    private int ifCentralStaff;
    private int numStatus;
    private String fileId;
    private String fileIds;
    private int quarter;
    private String quarterText;

    public String execute(){
        return "financialanalysis";
    }

    public String list(){
        pager = new Pager();
        if (rows <= 0){
            rows = 10;
        }
        pager.setPageSize(rows);
        pager.setPageNumber(page);
        pager.setOrderBy("createDate");
        pager.setOrderType(BaseEnum.OrderType.desc);

        if(StringUtils.isNotEmpty(sidx)&& BaseEnum.OrderType.valueOf(sord)!=null){
            pager.setOrderBy(sidx);
            pager.setOrderType(BaseEnum.OrderType.valueOf(sord));
        }
        Company com = usersService.getCompanyByUser();
        Map<String,Object> params = new HashMap<String,Object>();
        params = getSearchFilterParams(_search,params,filters);
        params.put("company",com);
        params.put("state", BaseEnum.StateEnum.Enable);
        //所有单子
        params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed, FlowEnum.ProcessState.Finished, FlowEnum.ProcessState.Deny});
        pager=financialAnalysisService.findByPagerAndLimit(true, "financialanalysis", pager, params);
        List<FinancialAnalysis> faList;
        if (pager.getTotalCount() > 0){
            faList = (List<FinancialAnalysis>) pager.getList();
        }else{
            faList = new ArrayList<>();
        }
        List<JSONObject> dataRows=new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;
        for(FinancialAnalysis f:faList){
            String state=f.getProcessState().name();
            rMap = new HashMap<String,Object>();
            switch (f.getQuarter()){
                case 1 :rMap.put("quarter","一季度");break;
                case 2 :rMap.put("quarter","半年");break;
                case 3 :rMap.put("quarter","三季度");break;
                case 4 :rMap.put("quarter","全年");break;
                default:rMap.put("quarter","未知");
            }
            rMap.put("id", f.getId());
            rMap.put("year", f.getYear());
            rMap.put("createDate", DataUtil.DateToString(f.getCreateDate(), "yyyy-MM-dd"));
            rMap.put("creater", f.getCreater() == null?"":f.getCreater().getName());
            if (StringUtils.isNotEmpty(f.getProcessState().name())) {
                rMap.put("state", f.getProcessState().value());
            }
            JSONObject o = JSONObject.fromObject(rMap);
            dataRows.add(o);
        }
        data.put("dataRows",dataRows);
        data.put("page",page);
        data.put("rows",rows);
        long recordsNum = pager.getTotalCount();
        data.put("total",calcPageNum(recordsNum));
        data.put("records", recordsNum);

        return  ajaxJson(JSONObject.fromObject(data).toString());
    }

    public String input(){
        if(StringUtils.isNotEmpty(keyId)){
            financialAnalysis=financialAnalysisService.get(keyId);
            fileId="";
            if(financialAnalysis.getFile()!=null&&financialAnalysis.getFile().size()>0){
                for(FileManage f:financialAnalysis.getFile()){
                    fileId+=f.getId()+",";
                }
            }
        }
        return "input";
    }

    public String save(){
        setData();
        try {
            if(StringUtils.isNotEmpty(keyId)){
                financialAnalysisService.update(financialAnalysis);
            } else {
                Map<String, Object> various = new HashMap<String, Object>();
                various.put("numStatus", 0);
                various.put("initDuty", curDutyId);
                various.put("curDutyId", curDutyId);
                financialAnalysisService.save(financialAnalysis, "financialanalysis", various);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }

        return ajaxHtmlCallback("200", "保存成功！", "操作状态");
    }

    public String read(){
        loginUser=usersService.getLoginInfo();
        if(StringUtils.isNotEmpty(keyId)){
            numStatus=workflowService.getNumStatus(keyId,loginUser);
            financialAnalysis=financialAnalysisService.get(keyId);
            fileId="";
            if(financialAnalysis.getFile()!=null&&financialAnalysis.getFile().size()>0){
                for(FileManage f:financialAnalysis.getFile()){
                    fileId+=f.getId()+",";
                }
            }
            switch (financialAnalysis.getQuarter()){
                case 1:quarterText="一季度";break;
                case 2:quarterText="半年";break;
                case 3:quarterText="三季度";break;
                case 4:quarterText="全年";break;
                default:quarterText="未知";
            }
        }
        return "read";
    }

    public void setData(){
        if(StringUtils.isNotEmpty(keyId)){
            financialAnalysis=financialAnalysisService.get(keyId);
        }else{
            financialAnalysis=new FinancialAnalysis();
            financialAnalysis.setCreater(usersService.getLoginInfo());
        }
        financialAnalysis.setQuarter(quarter);
        financialAnalysis.setCompany(usersService.getLoginInfo().getCompany());
        List<FileManage> fileList= Lists.newArrayList();
        if(StringUtils.isNotEmpty(fileIds)){
            for(String f:fileIds.split(",")){
                fileList.add(fileManageService.get(f.trim()));
            }
            financialAnalysis.setFile(fileList);
        }
        financialAnalysis.setYear(DataUtil.DateToString(new Date(),"yyyy"));
    }

    public String commit(){
        Company company = usersService.getCompanyByUser();
        Map<String,Object> params = new HashMap<String,Object>();
        params.put("processState", new FlowEnum.ProcessState[]{FlowEnum.ProcessState.Finished,FlowEnum.ProcessState.Running});
        params.put("year", DataUtil.DateToString(new Date(),"yyyy"));
        params.put("quarter", quarter);
        List<FinancialAnalysis> list = (List<FinancialAnalysis>)financialAnalysisService.findByPagerAndCompany(null, null, company, params).getList();
        if(list.size()>0){
            return ajaxHtmlCallback("400", "每个季度只能新建一次", "操作状态");
        }
        setData();
        ifCentralStaff=0;
        Map<String, Object> var1 = new HashMap<String, Object>();
        var1.put("numStatus", 0);
        var1.put("curDutyId", curDutyId);
        var1.put("initDuty", curDutyId);
        Map<String, Object> var2 = new HashMap<String, Object>();

        Set<Duty> dutySet = usersService.getLoginInfo().getDutySet();
        for (Duty duty:dutySet){
            if(duty.getDepartment().getParent()!=null){
                LogUtil.info("ceshi" + duty.getDepartment().getParent().getName());
                if(StringUtils.equals(duty.getDepartment().getParent().getName(),"产业中心")){
                    ifCentralStaff=1;
                    break;
                }
            }
        }
        if(ifCentralStaff==1){
            var1.put("numStatus",3);
            var2.put("numStatus",3);
        }else{
            var1.put("numStatus",1);
            var2.put("numStatus", 1);
        }
        var2.put("curDutyId", curDutyId);
        var2.put("ifCentralStaff", ifCentralStaff);
        List<String> list1=Lists.newArrayList();
        for(Duty duty:dutySet){
            Department dept=duty.getDepartment().getParent()==null?duty.getDepartment():duty.getDepartment().getParent();
            Set<Department> deptSet=dept.getChildren();
            for(Department cdept:deptSet){
                if(cdept.getName().contains("财务科")){
                    Set<Power> powers = cdept.getPowerSet();
                    for(Power power:powers){
                        if(power.getPost().getName().equals("科长")){
                            List<Users> usersList=dutyService.getPersons(cdept,power.getPost());
                            for(Users user:usersList){
                                list1.add(user.getId().trim());
                            }
                        }
                    }
                }

            }
        }
        var1.put("approver", list1);
        var2.put("approver", list1);
        List<String> list2=Lists.newArrayList();
        for(Duty duty:dutySet){
            Department dept=duty.getDepartment().getParent()==null?duty.getDepartment():duty.getDepartment().getParent();
            Set<Power> powers = dept.getPowerSet();
            for(Power power:powers){
                if(power.getPost().getName().equals("总经理")){
                    List<Users> usersList=dutyService.getPersons(dept,power.getPost());
                    for(Users user:usersList){
                        list2.add(user.getId().trim());
                    }
                }
            }
        }
        var1.put("approver1", list2);
        var2.put("approver1", list2);

        try {
            if (StringUtils.isNotEmpty(keyId)) {
                financialAnalysisService.approve(financialAnalysis, FlowEnum.ProcessState.Running, var2, curDutyId, comment);
            } else {
                keyId = financialAnalysisService.commit(financialAnalysis, "financialanalysis", var1, var2, curDutyId);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }

        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    public String approve1(){
        ifCentralStaff=0;
        financialAnalysis = financialAnalysisService.get(keyId);
        Map<String, Object> var1 = new HashMap<String, Object>();

        Set<Duty> dutySet = usersService.getLoginInfo().getDutySet();
        for (Duty duty:dutySet){
            if(duty.getDepartment().getParent()!=null){
                LogUtil.info("ceshi"+duty.getDepartment().getParent().getName());
                if(StringUtils.equals(duty.getDepartment().getParent().getName(),"产业中心")){
                    ifCentralStaff=1;
                    break;
                }
            }
        }
        var1.put("numStatus", 2);
        var1.put("curDutyId", curDutyId);

        if(StringUtils.isEmpty(comment)){
            comment="";
        }
        try {
            if (StringUtils.isNotEmpty(keyId)) {
                financialAnalysisService.approve(financialAnalysis, FlowEnum.ProcessState.Running, var1, curDutyId, comment);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }
        catch (Exception e){
            return ajaxHtmlCallback("404", "操作异常，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    public String approve2() {
        if(StringUtils.isEmpty(keyId))return ajaxHtmlCallback("404", "文档ID未找到！", "操作状态");
        if(StringUtils.isEmpty(comment)) comment="";
        financialAnalysis = financialAnalysisService.get(keyId);

        Map<String, Object> var2 = new HashMap<String, Object>();
        var2.put("numStatus", 3);
        //  var2.put("curDutyId", curDutyId);
        try {
            financialAnalysisService.approve(financialAnalysis, FlowEnum.ProcessState.Running, var2, curDutyId,comment);

        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }catch (Exception e){
            return ajaxHtmlCallback("404", "操作异常，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    public String approve3() {
        if(StringUtils.isEmpty(keyId))return ajaxHtmlCallback("404", "文档ID未找到！", "操作状态");
        if(StringUtils.isEmpty(comment)) comment="";
        financialAnalysis = financialAnalysisService.get(keyId);

        Map<String, Object> var2 = new HashMap<String, Object>();
        var2.put("numStatus", 4);
        //  var2.put("curDutyId", curDutyId);
        try {
            financialAnalysisService.approve(financialAnalysis, FlowEnum.ProcessState.Running, var2, curDutyId,comment);
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }catch (Exception e){
            return ajaxHtmlCallback("404", "操作异常，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    public String approve4() {
        if(StringUtils.isEmpty(keyId))return ajaxHtmlCallback("404", "文档ID未找到！", "操作状态");
        if(StringUtils.isEmpty(comment)) comment="";
        financialAnalysis = financialAnalysisService.get(keyId);

        Map<String, Object> var2 = new HashMap<String, Object>();
        var2.put("numStatus", 5);
        //  var2.put("curDutyId", curDutyId);
        try {
            financialAnalysisService.approve(financialAnalysis, FlowEnum.ProcessState.Finished, var2, curDutyId,comment);
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }catch (Exception e){
            return ajaxHtmlCallback("404", "操作异常，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    /**
     * 退回
     * @return
     */
    public String reject() {
        if (com.joint.base.util.StringUtils.isNotEmpty(keyId)) {
            financialAnalysis = financialAnalysisService.get(keyId);
            List<ActivityImpl> activityList= workflowService.findAllActivitiesByKey("financialanalysis");
            String key=activityList.get(0).getId();
            System.out.println("Activity key:"+key);
            System.out.println("comment:"+comment);
            LogUtil.info("numStatus:" + numStatus);
            if(StringUtils.isEmpty(comment)) comment="";
            financialAnalysisService.reject(financialAnalysis, key, numStatus, comment, curDutyId);
        }
        return ajaxHtmlCallback("200", "退回成功！", "操作状态");
    }

    /**
     * 否决
     * @return
     */
    public String deny() {
        if (com.joint.base.util.StringUtils.isNotEmpty(keyId)) {
            financialAnalysis = financialAnalysisService.get(keyId);
            List<ActivityImpl> activityList= workflowService.findAllActivitiesByKey("financeyear");
            String key= activityList.get(activityList.size()-1).getId();
            System.out.println("Activity key:" + key);
            if(com.joint.base.util.StringUtils.isEmpty(comment)){
                comment="";
            }
            financialAnalysisService.deny(financialAnalysis, key, comment, curDutyId);
        }
        return ajaxHtmlCallback("200", "否决成功！", "操作状态");
    }


    public FinancialAnalysis getFinancialAnalysis() {
        return financialAnalysis;
    }

    public void setFinancialAnalysis(FinancialAnalysis financialAnalysis) {
        this.financialAnalysis = financialAnalysis;
    }

    public Users getLoginUser() {
        return loginUser;
    }

    public void setLoginUser(Users loginUser) {
        this.loginUser = loginUser;
    }

    public String getViewtype() {
        return viewtype;
    }

    public void setViewtype(String viewtype) {
        this.viewtype = viewtype;
    }

    public int getIfCentralStaff() {
        return ifCentralStaff;
    }

    public void setIfCentralStaff(int ifCentralStaff) {
        this.ifCentralStaff = ifCentralStaff;
    }

    @Override
    public int getNumStatus() {
        return numStatus;
    }

    @Override
    public void setNumStatus(int numStatus) {
        this.numStatus = numStatus;
    }

    public String getFileId() {
        return fileId;
    }

    public void setFileId(String fileId) {
        this.fileId = fileId;
    }

    public String getFileIds() {
        return fileIds;
    }

    public void setFileIds(String fileIds) {
        this.fileIds = fileIds;
    }

    public int getQuarter() {
        return quarter;
    }

    public void setQuarter(int quarter) {
        this.quarter = quarter;
    }

    public String getQuarterText() {
        return quarterText;
    }

    public void setQuarterText(String quarterText) {
        this.quarterText = quarterText;
    }
}
